<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="班级名称" prop="classesName">
        <el-input v-model.trim="formData.classesName" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="班级编码" prop="classesCode">
        <el-input v-model.trim="formData.classesCode" placeholder="请输入班级编码" />
      </el-form-item>
      <el-form-item label="学校名称" prop="schoolId" v-if="infoType">
        <el-select
          @change="schoolChange"
          v-model.trim="formData.schoolId"
          clearable
          filterable
          placeholder="请选择学校"
          class="!w-240px"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.id"
            :label="item.schoolName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机构名称" prop="collegeId" v-if="infoType">
        <el-select
          v-model.trim="formData.collegeId"
          clearable
          filterable
          placeholder="请选择机构"
          :disabled="!formData.schoolId"
          @change="changeCollege"
          class="!w-240px"
        >
          <el-option
            v-for="item in collegeList"
            :key="item.id"
            :label="item.collegeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业名称" prop="majorId" v-if="infoType">
        <el-select
          v-model.trim="formData.majorId"
          clearable
          filterable
          placeholder="请选择专业"
          :disabled="!formData.schoolId"
          class="!w-240px"
        >
          <el-option
            v-for="item in majorList"
            :key="item.id"
            :label="item.majorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入学年份" prop="beginYear">
        <el-input v-model.trim="formData.beginYear" placeholder="请输入入学年份" maxLength="50" />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="formData.grade" placeholder="请选择" class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CMIS_GRADE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="阶段编号" prop="stageId">-->
      <!--        <el-input v-model.trim="formData.stageId" placeholder="请输入阶段编号" maxLength="50" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="开始年度" prop="startYear">-->
      <!--        <el-input v-model.trim="formData.startYear" placeholder="请输入开始年度" maxLength="50" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="开始时间" prop="startDate">-->
      <!--        <el-date-picker-->
      <!--          v-model="formData.startDate"-->
      <!--          type="date"-->
      <!--          value-format="x"-->
      <!--          placeholder="选择开始时间"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="结束结束" prop="endDate">-->
      <!--        <el-date-picker-->
      <!--          v-model="formData.endDate"-->
      <!--          type="date"-->
      <!--          value-format="x"-->
      <!--          placeholder="选择结束结束"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="状态" prop="status">-->
      <!--        <el-select v-model="formData.status" placeholder="请选择">-->
      <!--          <el-option-->
      <!--            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as ClassesApi from '@/api/cmis/classes'
import * as SchoolApi from '@/api/cmis/school'
import * as CollegeApi from '@/api/cmis/college'
import * as MajorApi from '@/api/cmis/major'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const infoType = ref(true) // 编辑时隐藏下拉状态

const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  classesName: undefined,
  classesCode: undefined,
  schoolId: undefined,
  collegeId: undefined,
  majorId: undefined,
  beginYear: undefined,
  grade: undefined,
  stageId: undefined,
  startYear: undefined,
  startDate: undefined,
  endDate: undefined,
  status: undefined
})
const formRules = reactive({
  classesName: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
  classesCode: [{ required: true, message: '班级编码不能为空', trigger: 'blur' }],
  schoolId: [{ required: true, message: '学校id不能为空', trigger: 'blur' }],
  grade: [{ required: true, message: '年级不能为空', trigger: 'blur' }]

  // collegeId: [{ required: true, message: '机构id不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const schoolList = ref([]) //学校列表
const collegeList = ref([]) //机构列表
const majorList = ref([]) //专业列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ClassesApi.getClasses(id)
      infoType.value = false
    } finally {
      formLoading.value = false
    }
  } else {
    infoType.value = true
  }
  // 加载学校列表
  schoolList.value = await SchoolApi.getSchoolList('')
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const schoolChange = async (value: any) => {
  formData.value.collegeId = undefined
  if (value) {
    // 加载机构列表并开启选择
    collegeList.value = await CollegeApi.getCollegeList({ schoolId: value })
    getMajorList()
  }
}

const changeCollege = async () => {
  formData.value.majorId = undefined
  getMajorList()
}

const getMajorList = async () => {
  const res = await MajorApi.getMajorList({
    schoolId: formData.value.schoolId,
    collegeId: formData.value.collegeId
  })
  majorList.value = res
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ClassesApi.ClassesVO
    if (formType.value === 'create') {
      await ClassesApi.createClasses(data)
      message.success(t('common.createSuccess'))
    } else {
      await ClassesApi.updateClasses(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    classesName: undefined,
    classesCode: undefined,
    schoolId: undefined,
    collegeId: undefined,
    majorId: undefined,
    beginYear: undefined,
    grade: undefined,
    stageId: undefined,
    startYear: undefined,
    startDate: undefined,
    endDate: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}
</script>
